package de.bensoft.jrail.business.service;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.bensoft.jrail.business.entity.Setting;

public class SettingsService {
	
	// Identifier ...
	public final static String SETTING_BAUD = "baudrate";
	public final static String SETTING_PORT = "port";
	
	private static final Logger log = Logger.getLogger(SettingsService.class);
	
	
	@Inject
	EntityManager em;
	
	public Setting findSettingByIdentifier(String identifier) {
		Query q = em.createNamedQuery(Setting.FIND_BY_IDENTIFIER);
		q.setParameter(Setting.BINDING_IDENTIFIER, identifier);
		
		Setting s = null;
		try {
			s = (Setting)q.getSingleResult();
		} catch(NoResultException ex) { log.info(ex); }
		
		if(s == null) {
			s = new Setting();
			s.setIdentifier(identifier);
		}
		
		return s;
	}
	
	public void saveSetting(Setting s) {
		
		em.getTransaction().begin();
		
		if(s.getId() != null)
			em.merge(s);
		else
			em.persist(s);
		
		em.getTransaction().commit();
	}
}
